<template>
    <Modal 
        :model-value="visible" 
        @update:model-value="emit('update:visible', $event)"
        title="新增用户"
        :loading="loading"
        :closable="false"
    >
        <Form ref="formRef" :model="formData" :rules="rules" :label-width="80">
            <FormItem label="用户名" prop="username">
                <Input v-model="formData.username" placeholder="请输入手机号" />
            </FormItem>
            <FormItem label="密码" prop="password">
                <Input 
                    v-model="formData.password" 
                    type="password" 
                    placeholder="请输入密码"
                    show-password
                />
            </FormItem>
            <FormItem label="昵称" prop="nickname">
                <Input v-model="formData.nickname" placeholder="请输入昵称" />
            </FormItem>
            <FormItem label="角色" prop="roleid">
                <Select v-model="formData.roleid">
                    <Option :value="1">超级管理</Option>
                    <Option :value="2">股票选手</Option>
                </Select>
            </FormItem>
            <FormItem label="状态" prop="status">
                <Select v-model="formData.status">
                    <Option :value="1">启用</Option>
                    <Option :value="0">禁用</Option>
                </Select>
            </FormItem>
        </Form>
    </Modal>
</template>

<script setup>
import { ref } from 'vue'
import { Message } from 'view-ui-plus'

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['update:visible', 'success'])

// 表单ref
const formRef = ref(null)
const loading = ref(false)

// 表单数据
const formData = ref({
    username: '',
    password: '',
    nickname: '',
    roleid: 2,
    status: 1  // 默认启用
})

// 表单校验规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
    ],
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' }
    ],
    roleid: [
        { required: true, message: '请选择角色', trigger: 'change' }
    ]
}

// 提交表单
const handleSubmit = () => {
    formRef.value.validate((valid) => {
        if (!valid) {
            loading.value = true
            return
        }
        emit('success', formData.value)
        handleCancel()
    })
}

// 关闭弹窗
const handleCancel = () => {
    emit('update:visible', false)
    formRef.value?.resetFields()
    loading.value = true
}
</script>
